package org.fujay.langchain4jserver.application.listener;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.fujay.langchain4jserver.domain.application.event.AppConfigChangedEvent;
import org.fujay.langchain4jserver.domain.shared.service.CacheProvider;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * 应用配置变更事件监听器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AppConfigChangedEventListener {

    private final CacheProvider cacheProvider;

    /**
     * 处理应用配置变更事件
     *
     * @param event 事件对象
     */
    @Async
    @EventListener
    public void handleAppConfigChanged(AppConfigChangedEvent event) {
        log.info(
                "接收到应用配置变更事件: AppId={}, 新版本={}, 新配置快照={}",
                event.getAppId(),
                event.getNewVersion(),
                event.getNewConfigSnapshot());
        try {
            log.info("[审计] 应用 {} 配置已变更至版本 {}。", event.getAppId().value(), event.getNewVersion().value());

            String appCacheKey = "app_config:" + event.getAppId().value();
            boolean removed = cacheProvider.remove(appCacheKey);
            if (removed) {
                log.info("已清理应用 {} 的配置缓存 (Key: {})", event.getAppId().value(), appCacheKey);
            } else {
                log.warn("尝试清理应用 {} 的配置缓存，但未找到或删除失败 (Key: {})", event.getAppId().value(), appCacheKey);
            }

            log.info("应用配置变更事件处理成功: AppId={}", event.getAppId());

        } catch (Exception e) {
            log.error("处理应用配置变更事件时发生异常: AppId={}, Error: {}", event.getAppId(), e.getMessage(), e);
        }
    }
}
